#!/usr/bin/env bash
#
# 作用：检测 .dev_env → 生成 build → CMake 构建 → 设置 LD_LIBRARY_PATH → 运行指定目标
#
# 选项：
#   -t, --target [sample|gen_esb]  指定要构建和运行的目标（默认: sample）
#   -h, --help                     显示帮助信息
#

set -euo pipefail

# ---------- 函数定义 ----------
usage() {
    cat <<EOF
Usage: $0 [OPTIONS]

选项:
  -t, --target TARGET   指定要构建和运行的目标 (sample 或 gen_esb)
  -h, --help            显示此帮助信息

默认行为:
  当未指定目标时，默认构建并运行 sample
EOF
    exit 0
}

# 默认目标
TARGET="sample"

# ---------- 解析命令行参数 ----------
while [[ $# -gt 0 ]]; do
    case "$1" in
        -t|--target)
            TARGET="$2"
            shift 2
            ;;
        -h|--help)
            usage
            ;;
        *)
            echo "未知选项: $1" >&2
            usage
            exit 1
            ;;
    esac
done

# 验证目标有效性
VALID_TARGETS=("sample" "gen_esb")
# shellcheck disable=SC2199
# shellcheck disable=SC2076
if [[ ! " ${VALID_TARGETS[@]} " =~ " ${TARGET} " ]]; then
    echo "错误: 无效目标 '${TARGET}'。有效目标: ${VALID_TARGETS[*]}" >&2
    exit 1
fi

echo "[Info] 目标设置为: ${TARGET}"

# ---------- 1. 检查 .dev_env ----------
if [[ ! -f ".dev_env" ]]; then
  echo "ERROR: 找不到 .dev_env，请先执行 ./prepare_dev_env.sh 准备编译环境！" >&2
  exit 1
fi

# ---------- 2. 解析 .dev_env ----------
# 仅接受 KEY=VALUE，无空格、无注释
declare -A DEV_VARS
while IFS='=' read -r key value; do
  # 跳过空行及注释
  [[ -z "${key// /}" || "${key:0:1}" == "#" ]] && continue
  DEV_VARS["$key"]="$value"
done < .dev_env

# 必要变量检查
ASCEND_INSTALL_PATH=${DEV_VARS[ASCEND_INSTALL_PATH]:-}
if [[ -z "${ASCEND_INSTALL_PATH}" ]]; then
  echo "ERROR: .dev_env 中缺少 ASCEND_INSTALL_PATH 变量" >&2
  exit 1
fi

ASCEND_LIB_DIR="${ASCEND_INSTALL_PATH}/latest/lib64"
echo "[Info] ASCEND_LIB_DIR = ${ASCEND_LIB_DIR}"

# ---------- 3. 生成 build 目录并 CMake ----------
BUILD_DIR="build"
if [[ ! -d "${BUILD_DIR}" ]]; then
  echo "[Info] 创建构建目录 ${BUILD_DIR}"
  mkdir -p "${BUILD_DIR}"
  echo "[Info] 生成 CMake 构建文件"
  cmake -S . -B "${BUILD_DIR}" -DCMAKE_BUILD_TYPE=Release
fi

# ---------- 4. 编译指定目标 ----------
echo "[Info] 开始编译目标: ${TARGET}"
cmake --build "${BUILD_DIR}" --target "${TARGET}" -j"$(nproc)"

# ---------- 5. 设置 LD_LIBRARY_PATH ----------
export LD_LIBRARY_PATH="${ASCEND_LIB_DIR}:${LD_LIBRARY_PATH:-}"
echo "[Info] LD_LIBRARY_PATH 已设置为: ${LD_LIBRARY_PATH}"

# ---------- 6. 运行指定目标 ----------
echo "[Info] 运行 ${BUILD_DIR}/${TARGET}"

case "${TARGET}" in
    sample)
        "${BUILD_DIR}/sample"
        echo "[Success] sample 执行成功，pbtxt dump 已生成在当前目录。该文件以 ge_onnx_ 开头，可以在 netron 中打开显示"
        ;;
    gen_esb)
        ASCEND_OPP_PATH="${ASCEND_INSTALL_PATH}/latest/ops"
        echo "[Info] ASCEND_OPP_PATH = ${ASCEND_OPP_PATH}"
        export ASCEND_OPP_PATH="${ASCEND_OPP_PATH}"
        echo "[Info] ASCEND_OPP_PATH 已设置为: ${ASCEND_OPP_PATH}"
        "${BUILD_DIR}/tensor_graph_generation/ops_collector/gen_esb"
        echo "[Success] gen_esb 执行成功, 生成产物在当前目录下all_ops.h all_ops.cc all_ops_cpp.h！"
        ;;
esac